﻿using XinLife.Application.Interface;
using XinLife.Model;
using System.Data;
using XinLife.Core.Extention;
using XinLife.Core.Model;
using SqlSugar;
using System.Net.NetworkInformation;
using XinLife.Core.Helper;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace XinLife.Application.Implement
{
    public class SystemConfigService : BaseService, ISystemConfigService
    {
        public SystemConfigService(IBaseRepository baseRepository) : base(baseRepository) { }

        public async Task<AjaxResult> DelSystemConfig(string ids)
        {
            var r = await _db.Deleteable<SystemConfig>().In(ids.Split(',')).ExecuteCommandAsync();
            if (r > 0)
            {
                return Success("删除成功");
            }
            else
            {
                return Success("删除失败");
            }
        }

        public async Task<AjaxResult> EditSystemConfig(SystemConfig systemConfig)
        {
            if (string.IsNullOrWhiteSpace(systemConfig.cId))
            {
                await _db.Insertable(systemConfig).ExecuteCommandAsync();
                return Success("添加成功");
            }
            else
            {
                var old = await _db.Queryable<SystemConfig>().FirstAsync(t => t.cId == systemConfig.cId);
                systemConfig.cCreatedBy = old.cCreatedBy;
                systemConfig.cCreatedDate = old.cCreatedDate;

                await _db.Updateable<SystemConfig>(systemConfig).ExecuteCommandAsync();
                return Success("修改成功");
            }
        }

        public async Task<AjaxResult> GetSystemConfigForm(string id)
        {
            var data = await _db.Queryable<SystemConfig>().FirstAsync(t => t.cId == id);
            return Success(data);
        }

        public async Task<PageData<SystemConfig>> GetSystemConfigPageList(Pagination page, string queryJson)
        {
            var queryParam = queryJson.ToJObject();
            string? cName = queryParam.Value<string>("name");

            RefAsync<int> totalCount = 0;
            var users = await _db.Queryable<SystemConfig>()
                                .WhereIF(!cName.IsEmpty(), a => a.cName.Contains(cName))
                                .ToPageListAsync(page.pageIndex, page.pageSize, totalCount);

            return new PageData<SystemConfig>()
            {
                count = totalCount,
                entitys = users
            };
        }
        public Task<DataTable> GetTableToExecl(string queryJson)
        {
            var queryParam = queryJson.ToJObject();
            string? cName = queryParam.Value<string>("name");

            return _db.Queryable<SystemConfig>()
                      .WhereIF(!cName.IsEmpty(), a => a.cName.Contains(cName))
                      .ToDataTableAsync();
        }
    }
}
